class UnionFind
{
private:
    vector<int> parent;
    vector<int> size;
    
public:
    int setcount;               // 联通集的数量
    UnionFind(int n): setcount(n), parent(n), size(n, 1)
    {
        iota(parent.begin(), parent.end(), 0);
    }
    int findset(int x)
    {
        return parent[x] == x ? x : parent[x] = findset(parent[x]);
    }
    void unite(int x, int y)
    {
        x = findset(x), y = findset(y);
        if (x == y)
        {
            return;
        }

        if (size[x] < size[y])
        {
            swap(x, y);
        }
        parent[y] = x;
        size[x] += size[y];
        --setcount;
        return;
    }
    bool connected(int x, int y)
    {
        return findset(x) == findset(y);
    }
};
class Solution 
{
public:
    int makeConnected(int n, vector<vector<int>>& connections) 
    {
        if (n - 1 >connections.size())
        {
            return -1;
        }

        UnionFind uf(n);
        for (vector<vector<int>>::iterator iter = connections.begin(); iter != connections.end(); iter++)
        {
            if (!uf.connected((*iter)[0], (*iter)[1]))
            {
                uf.unite((*iter)[0], (*iter)[1]);
            }
        }
        return uf.setcount - 1;
    }
};